<template>
  <div class="checkout-page">
    <HeaderNav />
    
    <div class="container" v-loading="loading">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/cart' }">购物车</el-breadcrumb-item>
        <el-breadcrumb-item>订单结算</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="checkout-content" v-if="cartList.length > 0">
        <!-- 收货信息 -->
        <div class="info-card">
          <div class="card-title-wrapper">
            <h3 class="card-title">收货信息</h3>
            <el-button 
              v-if="addressList.length > 0" 
              type="primary" 
              link 
              @click="showAddressSelector = true"
            >
              <span class="btn-icon">📍</span>
              选择已保存的地址
            </el-button>
          </div>
          
          <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="收货人姓名" prop="receiverName">
              <el-input v-model="form.receiverName" placeholder="请输入收货人姓名" />
            </el-form-item>
            <el-form-item label="联系电话" prop="receiverPhone">
              <el-input v-model="form.receiverPhone" placeholder="请输入联系电话" />
            </el-form-item>
            <el-form-item label="收货地址" prop="receiverAddress">
              <el-input
                v-model="form.receiverAddress"
                type="textarea"
                :rows="3"
                placeholder="请输入详细收货地址"
              />
            </el-form-item>
            <el-form-item label="订单备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="2"
                placeholder="选填，有什么特殊要求可以在这里说明"
              />
            </el-form-item>
          </el-form>
        </div>

        <!-- 订单商品 -->
        <div class="info-card">
          <h3 class="card-title">订单商品</h3>
          <div class="order-items">
            <div
              v-for="item in cartList"
              :key="item.id"
              class="order-item"
            >
              <img
                :src="getImageUrl(item.product?.mainImage)"
                :alt="item.product?.productName"
                class="item-image"
                @error="handleImageError"
              />
              <div class="item-info">
                <h4 class="item-name">{{ item.product?.productName }}</h4>
                <div class="item-spec">
                  <span>单价：¥{{ formatPrice(item.product?.price) }}</span>
                  <span>数量：{{ item.quantity }}</span>
                </div>
              </div>
              <div class="item-total">
                ¥{{ formatPrice(item.product?.price ? item.product.price * item.quantity : 0) }}
              </div>
            </div>
          </div>
        </div>

        <!-- 订单汇总 -->
        <div class="info-card">
          <h3 class="card-title">订单汇总</h3>
          <div class="order-summary">
            <div class="summary-item">
              <span class="label">商品总价：</span>
              <span class="value">¥{{ formatPrice(totalAmount) }}</span>
            </div>
            <div class="summary-item">
              <span class="label">优惠金额：</span>
              <span class="value">¥0.00</span>
            </div>
            <div class="summary-item total">
              <span class="label">实付金额：</span>
              <span class="value">¥{{ formatPrice(totalAmount) }}</span>
            </div>
          </div>
        </div>

        <!-- 提交订单 -->
        <div class="checkout-footer">
          <div class="footer-left">
            <el-button @click="$router.back()">返回购物车</el-button>
          </div>
          <div class="footer-right">
            <div class="total-info">
              <span class="total-label">实付金额：</span>
              <span class="total-price">¥{{ formatPrice(totalAmount) }}</span>
            </div>
            <el-button
              type="danger"
              size="large"
              :loading="submitting"
              @click="handleSubmit"
            >
              提交订单
            </el-button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-else description="购物车中没有选中的商品">
        <el-button type="primary" @click="$router.push('/cart')">去购物车</el-button>
      </el-empty>
    </div>

    <!-- 选择收货地址弹窗 -->
    <el-dialog
      v-model="showAddressSelector"
      title="选择收货地址"
      width="700px"
      class="address-selector-dialog"
    >
      <div v-loading="loadingAddress" class="address-list">
        <div 
          v-for="address in addressList" 
          :key="address.id"
          class="address-item"
          :class="{ 'selected': selectedAddressId === address.id }"
          @click="handleSelectAddress(address)"
        >
          <div class="address-content">
            <!-- 默认标签 -->
            <el-tag v-if="address.isDefault === 1" class="default-tag" type="success" size="small">
              默认
            </el-tag>
            
            <!-- 收货人信息 -->
            <div class="receiver-info">
              <span class="receiver-name">{{ address.receiverName }}</span>
              <span class="receiver-phone">{{ address.receiverPhone }}</span>
            </div>
            
            <!-- 详细地址 -->
            <div class="address-detail">
              {{ address.fullAddress }}
            </div>
          </div>
          
          <!-- 选中标识 -->
          <div v-if="selectedAddressId === address.id" class="selected-icon">
            ✓
          </div>
        </div>
        
        <!-- 空状态 -->
        <el-empty 
          v-if="addressList.length === 0" 
          description="暂无收货地址"
          :image-size="80"
        >
          <el-button type="primary" @click="goToAddressManagement">
            去添加收货地址
          </el-button>
        </el-empty>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddressSelector = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleConfirmAddress"
            :disabled="!selectedAddressId"
          >
            确认使用
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import HeaderNav from '@/components/HeaderNav.vue'
import { getSelectedItems, calculateTotal } from '@/api/cart'
import { createOrder } from '@/api/order'
import { getAddressList } from '@/api/address'
import { getImageUrl, handleImageError as handleImgError } from '@/utils/image'

const router = useRouter()

const loading = ref(false)
const submitting = ref(false)
const loadingAddress = ref(false)
const cartList = ref([])
const formRef = ref(null)
const addressList = ref([])
const showAddressSelector = ref(false)
const selectedAddressId = ref(null)

const form = ref({
  receiverName: '',
  receiverPhone: '',
  receiverAddress: '',
  remark: ''
})

const rules = {
  receiverName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  receiverPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  receiverAddress: [
    { required: true, message: '请输入收货地址', trigger: 'blur' }
  ]
}

// 计算总金额
const totalAmount = computed(() => {
  return cartList.value.reduce((sum, item) => {
    const price = item.product?.price || 0
    return sum + price * item.quantity
  }, 0)
})

// 加载选中的购物车商品
const loadCartList = async () => {
  loading.value = true
  try {
    // 获取选中的购物车商品
    const res = await getSelectedItems()
    if (res.code === 200) {
      cartList.value = res.data || []
      if (cartList.value.length === 0) {
        ElMessage.warning('购物车中没有选中的商品')
        router.push('/cart')
      }
    }
  } catch (error) {
    ElMessage.error('加载购物车失败')
    router.push('/cart')
  } finally {
    loading.value = false
  }
}

// 加载收货地址列表
const loadAddressList = async () => {
  loadingAddress.value = true
  try {
    const response = await getAddressList()
    if (response.success) {
      addressList.value = response.data || []
      // 如果有默认地址，自动填充表单
      const defaultAddress = addressList.value.find(addr => addr.isDefault === 1)
      if (defaultAddress && !form.value.receiverName) {
        fillFormWithAddress(defaultAddress)
      }
    } else {
      console.error('获取地址列表失败:', response.message)
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
  } finally {
    loadingAddress.value = false
  }
}

// 使用地址填充表单
const fillFormWithAddress = (address) => {
  form.value.receiverName = address.receiverName
  form.value.receiverPhone = address.receiverPhone
  form.value.receiverAddress = address.fullAddress
  // 清除表单验证错误
  formRef.value?.clearValidate()
}

// 选择地址
const handleSelectAddress = (address) => {
  selectedAddressId.value = address.id
}

// 确认使用地址
const handleConfirmAddress = () => {
  const address = addressList.value.find(addr => addr.id === selectedAddressId.value)
  if (address) {
    fillFormWithAddress(address)
    showAddressSelector.value = false
    ElMessage.success('已选择收货地址')
  }
}

// 跳转到地址管理
const goToAddressManagement = () => {
  showAddressSelector.value = false
  router.push('/profile?tab=address')
}

// 处理提交订单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    const res = await createOrder({
      receiverName: form.value.receiverName,
      receiverPhone: form.value.receiverPhone,
      receiverAddress: form.value.receiverAddress,
      remark: form.value.remark
    })
    
    if (res.code === 200) {
      ElMessage.success('订单创建成功')
      // 后端已自动删除购物车中的商品，跳转到订单详情页
      router.push(`/order/${res.data}`)
    } else {
      ElMessage.error(res.message || '创建订单失败')
    }
  } catch (error) {
    if (error !== false) {
      ElMessage.error('创建订单失败')
    }
  } finally {
    submitting.value = false
  }
}

// 使用统一的图片错误处理
const handleImageError = handleImgError

// 格式化价格
const formatPrice = (price) => {
  if (!price) return '0.00'
  return Number(price).toFixed(2)
}

onMounted(() => {
  loadCartList()
  loadAddressList()
})
</script>

<style scoped lang="scss">
.checkout-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.checkout-content {
  .info-card {
    background: white;
    border-radius: 8px;
    padding: 30px;
    margin-bottom: 20px;
    
    .card-title-wrapper {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      border-bottom: 2px solid #f5f5f5;
      padding-bottom: 10px;
      
      .btn-icon {
        margin-right: 4px;
      }
    }
    
    .card-title {
      margin: 0 0 20px 0;
      font-size: 18px;
      color: #333;
      border-bottom: 2px solid #f5f5f5;
      padding-bottom: 10px;
    }
    
    .order-items {
      .order-item {
        display: flex;
        align-items: center;
        padding: 20px 0;
        border-bottom: 1px solid #eee;
        
        &:last-child {
          border-bottom: none;
        }
        
        .item-image {
          width: 100px;
          height: 100px;
          margin-right: 20px;
          border-radius: 4px;
          object-fit: cover;
        }
        
        .item-info {
          flex: 1;
          
          .item-name {
            font-size: 16px;
            margin: 0 0 10px 0;
            color: #333;
          }
          
          .item-spec {
            display: flex;
            gap: 20px;
            color: #999;
          }
        }
        
        .item-total {
          font-size: 18px;
          color: #f56c6c;
          font-weight: bold;
        }
      }
    }
    
    .order-summary {
      .summary-item {
        display: flex;
        justify-content: space-between;
        padding: 15px 0;
        border-bottom: 1px solid #eee;
        
        &:last-child {
          border-bottom: none;
        }
        
        &.total {
          border-top: 2px solid #eee;
          margin-top: 10px;
          padding-top: 20px;
          
          .label {
            font-size: 18px;
            font-weight: bold;
          }
          
          .value {
            font-size: 24px;
            color: #f56c6c;
            font-weight: bold;
          }
        }
        
        .label {
          color: #666;
        }
        
        .value {
          color: #333;
        }
      }
    }
  }
  
  .checkout-footer {
    background: white;
    border-radius: 8px;
    padding: 20px 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .footer-right {
      display: flex;
      align-items: center;
      gap: 20px;
      
      .total-info {
        .total-label {
          font-size: 16px;
          color: #666;
        }
        
        .total-price {
          font-size: 24px;
          color: #f56c6c;
          font-weight: bold;
          margin-left: 10px;
        }
      }
    }
  }
}

/* 地址选择弹窗 */
.address-selector-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
    max-height: 500px;
    overflow-y: auto;
  }
}

.address-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-height: 200px;
}

.address-item {
  background: white;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  position: relative;
  
  &:hover {
    border-color: #409EFF;
    background: #f0f9ff;
    transform: translateX(4px);
  }
  
  &.selected {
    border-color: #409EFF;
    background: #f0f9ff;
    box-shadow: 0 2px 12px rgba(64, 158, 255, 0.2);
  }
}

.address-content {
  flex: 1;
  position: relative;
}

.default-tag {
  position: absolute;
  top: -4px;
  right: 0;
  font-weight: 600;
}

.receiver-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 16px;
}

.receiver-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.receiver-phone {
  font-size: 14px;
  color: #606266;
}

.address-detail {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.selected-icon {
  width: 24px;
  height: 24px;
  background: #409EFF;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-weight: bold;
  font-size: 16px;
  flex-shrink: 0;
  margin-left: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .address-selector-dialog {
    :deep(.el-dialog) {
      width: 90%;
      margin: 0 auto;
    }
  }
  
  .address-item {
    flex-direction: column;
  }
  
  .selected-icon {
    position: absolute;
    top: 16px;
    right: 16px;
  }
}
</style>
